// 太阳能发电系统监控界面 - 共享JavaScript代码

// 全局应用数据
const appData = {
  // 设备状态
  isDeviceOn: true,
  showPowerDialog: false,
  pendingPowerState: null,
  lastUpdateTime: "2023-05-13 14:30",
  appLogo: "assets/透明底Logo.png",

  // 报警相关
  showAlert: false,
  alertMessage: "",

  // 天气数据
  weatherData: {
    location: "广东省江门市蓬江区",
    temperature: 28,
    humidity: 72,
    windSpeed: 2.6,
    rainChance: 30,
    weatherCondition: "cloudy", // sunny, cloudy, rainy, stormy
    lightIntensity: 65,
    lightEfficiencyText: "良好（预计达到75%效率）",
    forecast: [
      { day: "今天", temp: 28, condition: "cloudy", desc: "多云" },
      { day: "明天", temp: 30, condition: "sunny", desc: "晴天" },
      { day: "后天", temp: 26, condition: "rainy", desc: "小雨" },
    ],
  },

  // 发电数据
  powerData: {
    todayGeneration: 1.2,
    dailyTarget: 1.5,
    monthlyGeneration: 32.4,
    monthlyTrend: 8, // 同比上周增长百分比
    weeklyData: [
      { day: "一", value: 1.1 },
      { day: "二", value: 0.9 },
      { day: "三", value: 1.3 },
      { day: "四", value: 1.0 },
      { day: "五", value: 1.4 },
      { day: "六", value: 1.2 },
      { day: "日", value: 0.8 },
    ],
    hourlyData: [
      { hour: "06:00", value: 0.05 },
      { hour: "07:00", value: 0.1 },
      { hour: "08:00", value: 0.2 },
      { hour: "09:00", value: 0.4 },
      { hour: "10:00", value: 0.6 },
      { hour: "11:00", value: 0.8 },
      { hour: "12:00", value: 1.0 },
      { hour: "13:00", value: 1.1 },
      { hour: "14:00", value: 0.9 },
      { hour: "15:00", value: 0.7 },
      { hour: "16:00", value: 0.5 },
      { hour: "17:00", value: 0.3 },
      { hour: "18:00", value: 0.1 },
    ],
    maxHourlyValue: 1.1,
  },

  // 系统状态数据
  statusData: {
    voltage: 230,
    voltageStatus: "normal", // normal, warning, danger
    temperature: 52,
    temperatureStatus: "warning", // normal, warning, danger
    efficiency: 96.5,
    efficiencyStatus: "normal", // normal, warning, danger
  },

  // 电力分配数据
  distributionData: {
    home: 0.7,
    load: 0.5,
    homePercent: 58,
    loadPercent: 42,
    savingAmount: 0.42,
  },

  // 设置数据
  settingsData: {
    autoRefresh: true,
    refreshInterval: 30, // 秒
    darkMode: false,
    notificationsEnabled: true,
    dailyTargetValue: 1.5,
    temperatureUnit: "celsius", // celsius, fahrenheit
  },
};

// 共享方法
const appMethods = {
  // 更新最后更新时间
  updateLastUpdateTime() {
    const now = new Date();
    const hours = String(now.getHours()).padStart(2, "0");
    const minutes = String(now.getMinutes()).padStart(2, "0");
    const day = String(now.getDate()).padStart(2, "0");
    const month = String(now.getMonth() + 1).padStart(2, "0");
    const year = now.getFullYear();

    appData.lastUpdateTime = `${year}-${month}-${day} ${hours}:${minutes}`;
    return appData.lastUpdateTime;
  },

  // 计算环形进度条的周长
  calculateCircumference(radius) {
    return 2 * Math.PI * radius;
  },

  // 计算环形进度条的偏移量
  calculateDashOffset(current, target, circumference) {
    const progress = current / target;
    return circumference - progress * circumference;
  },

  // 根据天气状况返回对应的图标类
  getWeatherIconClass(condition) {
    switch (condition) {
      case "sunny":
        return "fas fa-sun";
      case "cloudy":
        return "fas fa-cloud";
      case "rainy":
        return "fas fa-cloud-rain";
      case "stormy":
        return "fas fa-bolt";
      default:
        return "fas fa-sun";
    }
  },

  // 切换电源状态（显示确认对话框）
  togglePower() {
    // 模拟震动反馈
    if ("vibrate" in navigator) {
      navigator.vibrate(100);
    }

    appData.pendingPowerState = !appData.isDeviceOn;
    appData.showPowerDialog = true;
  },

  // 取消电源操作
  cancelPowerAction() {
    appData.showPowerDialog = false;
    appData.pendingPowerState = null;
  },

  // 确认电源操作
  confirmPowerAction() {
    appData.isDeviceOn = appData.pendingPowerState;
    appData.showPowerDialog = false;

    // 如果设备已关闭，显示提示信息
    if (!appData.isDeviceOn) {
      this.showSystemAlert("设备已关闭，数据记录已停止");
    }
  },

  // 刷新天气数据
  refreshWeather() {
    // 模拟震动反馈
    if ("vibrate" in navigator) {
      navigator.vibrate(50);
    }

    // 模拟网络延迟
    setTimeout(() => {
      // 随机更新天气数据（真实应用中应调用天气API）
      appData.weatherData.temperature = Math.floor(Math.random() * 5) + 26; // 26-30度
      appData.weatherData.humidity = Math.floor(Math.random() * 15) + 65; // 65-80%
      appData.weatherData.windSpeed = (Math.random() * 3 + 1).toFixed(1); // 1-4 m/s
      appData.weatherData.rainChance = Math.floor(Math.random() * 35) + 5; // 5-40%

      // 根据随机数改变天气状况
      const weatherTypes = ["sunny", "cloudy", "rainy", "stormy"];
      const weightedTypes = [
        "sunny",
        "sunny",
        "sunny", // 较高概率晴天
        "cloudy",
        "cloudy",
        "cloudy",
        "cloudy", // 最高概率多云
        "rainy",
        "rainy", // 较低概率下雨
        "stormy", // 最低概率雷暴
      ];
      appData.weatherData.weatherCondition =
        weightedTypes[Math.floor(Math.random() * weightedTypes.length)];

      // 更新光照强度
      this.updateLightIntensity();

      // 更新最后更新时间
      this.updateLastUpdateTime();

      // 更新Vue实例中的数据（如果存在）
      if (typeof vm !== "undefined" && vm) {
        vm.weatherData = { ...appData.weatherData };
        vm.lastUpdateTime = appData.lastUpdateTime;
      }
    }, 500);
  },

  // 更新光照强度
  updateLightIntensity() {
    // 基于天气状况计算光照强度
    let baseIntensity = 0;
    switch (appData.weatherData.weatherCondition) {
      case "sunny":
        baseIntensity = 85;
        break;
      case "cloudy":
        baseIntensity = 60;
        break;
      case "rainy":
        baseIntensity = 30;
        break;
      case "stormy":
        baseIntensity = 15;
        break;
    }

    // 添加一些随机性
    appData.weatherData.lightIntensity = Math.min(
      100,
      baseIntensity + Math.floor(Math.random() * 15)
    );

    // 更新效率文本
    if (appData.weatherData.lightIntensity > 80) {
      appData.weatherData.lightEfficiencyText = "极佳（预计达到95%效率）";
    } else if (appData.weatherData.lightIntensity > 60) {
      appData.weatherData.lightEfficiencyText = "良好（预计达到80%效率）";
    } else if (appData.weatherData.lightIntensity > 40) {
      appData.weatherData.lightEfficiencyText = "一般（预计达到60%效率）";
    } else {
      appData.weatherData.lightEfficiencyText = "较差（预计达到40%以下效率）";
    }
  },

  // 显示系统报警
  showSystemAlert(message) {
    // 防止重复显示相同的报警
    if (appData.alertMessage !== message) {
      appData.alertMessage = message;
      appData.showAlert = true;

      // 模拟更强烈的震动
      if ("vibrate" in navigator) {
        navigator.vibrate([100, 50, 200, 50, 100]);
      }
    }
  },

  // 确认报警
  acknowledgeAlert() {
    appData.showAlert = false;
  },

  // 获取当前页面路径
  getCurrentPage() {
    const path = window.location.pathname;
    const pageName = path.split("/").pop().split(".")[0];
    return pageName || "index";
  },

  // 跳转到指定页面
  navigateTo(page) {
    console.log("尝试跳转到页面:", page);
    try {
      window.location.href = `${page}.html`;
    } catch (error) {
      console.error("页面跳转失败:", error);
    }
  },

  // 保存设置到localStorage
  saveSettingsToStorage() {
    try {
      localStorage.setItem(
        "solarAppSettings",
        JSON.stringify(appData.settingsData)
      );
    } catch (error) {
      console.error("保存设置失败:", error);
    }
  },

  // 从localStorage加载设置
  loadSettingsFromStorage() {
    try {
      const savedSettings = localStorage.getItem("solarAppSettings");
      if (savedSettings) {
        const parsedSettings = JSON.parse(savedSettings);
        Object.assign(appData.settingsData, parsedSettings);
      }
    } catch (error) {
      console.error("加载设置失败:", error);
    }
  },

  // 应用暗色模式
  applyDarkMode() {
    const rootElement = document.documentElement;

    if (appData.settingsData.darkMode) {
      rootElement.classList.add("dark-mode");
    } else {
      rootElement.classList.remove("dark-mode");
    }
  },

  // 切换暗色模式
  toggleDarkMode() {
    appData.settingsData.darkMode = !appData.settingsData.darkMode;
    this.applyDarkMode();
    this.saveSettingsToStorage();
  },
};

// 初始化功能
function initCommon() {
  try {
    // 从localStorage加载设置
    appMethods.loadSettingsFromStorage();

    // 应用暗色模式
    appMethods.applyDarkMode();

    // 添加当前页面的激活状态
    const currentPage = appMethods.getCurrentPage();
    const navItems = document.querySelectorAll(".nav-item");

    if (navItems.length === 0) {
      console.warn("未找到导航元素");
      return;
    }

    navItems.forEach((item) => {
      const page = item.getAttribute("data-page");
      if (!page) {
        console.warn("导航元素缺少data-page属性");
        return;
      }

      if (page === currentPage) {
        item.classList.add("active");
      }

      // 移除之前的事件监听器（如果有的话）
      item.removeEventListener("click", item._navClickHandler);

            // 添加导航事件
      item._navClickHandler = (event) => {
        // 阻止事件冒泡，避免与Vue事件冲突
        event.preventDefault();
        event.stopPropagation();
        
        if (page !== currentPage) {
          console.log("导航到页面:", page);
          appMethods.navigateTo(page);
        }
      };
      
      item.addEventListener("click", item._navClickHandler);
    });

    console.log("导航初始化完成，当前页面:", currentPage);
  } catch (error) {
    console.error("初始化导航时出错:", error);
  }
}

// 当页面加载完成时执行初始化
document.addEventListener("DOMContentLoaded", () => {
  // 延迟一点执行，确保Vue实例已经初始化
  setTimeout(initCommon, 100);
});

// 也监听window的load事件，确保所有资源都加载完成
window.addEventListener("load", () => {
  setTimeout(initCommon, 50);
});
